package com.lxw.sso.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.lxw.sso.server.core.model.User;
import com.lxw.sso.server.core.model.UserInfo;
import com.lxw.sso.server.core.result.ReturnT;
import com.lxw.sso.server.mapper.UserMapper;
import com.lxw.sso.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ReturnT<UserInfo> findUser(String username, String password) {

        if (username==null || username.trim().length()==0) {
            return new ReturnT<UserInfo>(ReturnT.FAIL_CODE, "Please input username.");
        }
        if (password==null || password.trim().length()==0) {
            return new ReturnT<UserInfo>(ReturnT.FAIL_CODE, "Please input password.");
        }

        Map<String,Object> colMap=new HashMap<>();
        colMap.put("USER_NAME",username);
        colMap.put("PASSWORD",password);
        List<User> userList = userMapper.selectByMap(colMap);
        if(CollectionUtils.isEmpty(userList)){
            return new ReturnT<UserInfo>(ReturnT.FAIL_CODE, "username or password is invalid");
        }

        if(userList.size()>1){
            return new ReturnT<UserInfo>(ReturnT.FAIL_CODE, "your account have some problems,please concat admin");
        }

        User user=userList.get(0);

        UserInfo userInfo=new UserInfo();
        userInfo.setUserid(user.getId());
        userInfo.setUsername(user.getUserName());

        Map<String,String> userData=new HashMap<>();
        userData.put("nickName",user.getNickName());
        userData.put("mobile",user.getMobile());
        userData.put("cover",user.getCover());
        userData.put("description",user.getDescription());
        userInfo.setUserData(JSON.toJSONString(userData));

        return new ReturnT<UserInfo>(userInfo);
    }


}
